﻿using CloOpenSDK;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Configuration;
using Sino.CapacityCloud.Services.Models;
using Sino.Common.Utilities;
using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace Sino.CapacityCloud.Services
{

    /// <summary>
    /// 通知消费对象
    /// 提供容联短信发送服务
    /// 具体请参阅（http://www.yuntongxun.com/activity/smsDevelop#tiyan）
    /// </summary>
    public class SmsSender
        : ConfigurableServiceBase, ISmsSender
    {

        private readonly SMSSDK _smsSdk;
        private readonly string _address;
        private readonly string _port;
        private readonly string _accountSid;
        private readonly string _accountToken;
        private readonly string _appId;

        public SmsSender(IHostingEnvironment env)
            : base(env, section: "Data:DefaultConnection:CloOpenConnection")
        {
            this._address = this.Configuration["Address"];
            this._port = this.Configuration["Port"];
            this._accountSid = this.Configuration["AccountId"];
            this._accountToken = this.Configuration["AccountToken"];
            this._appId = this.Configuration["AppId"];

            this._smsSdk = new SMSSDK(this._address, this._port, this._accountSid, this._accountToken, this._appId);
        }

        public bool ValidatePhoneFormat(string phoneNumber)
        {
            return phoneNumber.IsPhoneNumber();
        }

        protected async Task<SMSResult> SendSms(SmsDom csd)
        {
            var strPhones = string.Join(",", csd.PhoneLists);
            var result = await _smsSdk.SendTemplateSMS(strPhones, csd.TemplateID, csd.TemplateData.ToArray());
            return result;
        }

        public void SendSms(string phonNumber, string code)
        {
            this.SendSmsAsync(phonNumber, code).GetAwaiter().GetResult();
        }

        public async Task<SmsRequestResult> SendSmsAsync(string phonNumber, string message)
        {
            if (!this.ValidatePhoneFormat(phonNumber))
            {
                throw new ArgumentOutOfRangeException("phonNumber");
            }
            SmsDom dom = new SmsDom();
            dom.PhoneLists.Add(phonNumber);
            dom.TemplateID = "27026";
            dom.TemplateData.Add(message);
            dom.TemplateData.Add("2");
            var r = await SendSms(dom);
            switch (r.statusCode)
            {
                case "000000":
                    return SmsRequestResult.Success;

                case "172002":
                    return SmsRequestResult.WrongPhoneNumber;

                case "172003":
                    return SmsRequestResult.ServerError;

                default:
                    return SmsRequestResult.ServerError;
            }
        }

    }

}